<template>
    <view>
        <!-- subpackage/book/book.wxml -->
        <custom-navbar :showTitle="false" backgroundColor="#ffffff" textColor="#ffffff" :showBack="true"
            :isCoverNav="false"></custom-navbar>
        <view class="bookPage" :style="'height: calc(100vh - ' + navHeight + 'px - 172rpx);'">
            <view class="bookPage_info">
                <view class="bookPage_info_left">
                    <image :src="roomInfo.cover" mode="" />
                </view>
                <view class="bookPage_info_right">
                    <text>{{ roomInfo.name }}</text>
                    <view v-if="roomInfo.config && roomInfo.config != ''" class="roomList-desc">
                        <view v-for="(item, index) in jsonToArray('config', roomInfo.config)" :key="index">
                            <text>{{ item.text }}</text> <text v-if="index != jsonToArray('config', roomInfo.config).length - 1">·</text>
                        </view>
                    </view>
                </view>
            </view>
            <view class="bookPage_form">
                <up-form labelPosition="left" :model="formData" ref="formRef" :rules="rules" labelWidth="100">
                    <up-form-item label="入住日期" prop="datetimeText" borderBottom @click="showCalendar = true; hideKeyboard()">
                        <up-input v-model="formData.datetimeText" disabled disabledColor="#ffffff" placeholder="请选择入住和退房日期" border="none" fontSize="24rpx"></up-input>
                        <template #right>
                            <up-icon name="arrow-right"></up-icon>
                        </template>
                    </up-form-item>
                    <up-form-item label="预约人姓名" prop="name" borderBottom >
                        <up-input v-model="formData.name" border="none" placeholder="姓名,只能为中文"></up-input>
                    </up-form-item>
                    <up-form-item label="入住人数" prop="number" borderBottom >
                        <up-input v-model="formData.number" border="none" placeholder="请输入人数"></up-input>
                    </up-form-item>
                    <!-- <up-form-item label="身份证号" prop="card_no" borderBottom ref="item2">
                        <up-input v-model="formData.card_no" border="none" placeholder="身份证号"></up-input>
                    </up-form-item> -->
                    <up-form-item label="预约电话" prop="mobile"  >
                        <up-input v-model="formData.mobile" border="none" placeholder="电话号"></up-input>
                    </up-form-item>
                </up-form>
                
            </view>
            <view class="bookPage_explain">
                <text class="bookPage_explain_title">下单说明</text>
                <text>订单提交成功并支付后，商家将尽快处理订单，如有延迟，敬请谅解。若商户拒单，支付款项及资产将原路返回至您的账户，到账时间以各支付通道退款处理时间为准。</text>
            </view>
            <view class="bookPage_footer">
                <view class="bookPage_footer_left">
                    <text class="bookPage_footer_left_price">￥ {{ roomInfo.price }}</text>
                    <!-- <view class="bookPage_footer_left_particulars">
                        <text>明细</text>
                        <image src="https://image.shengxuankj.com/fronts/downArrow.png" mode="" />
                    </view> -->
                </view>
                <view class="bookPage_footer_right">
                    <up-button color="rgba(57, 97, 54, 1)" round custom-class="btn"
                        @tap.native="goToPayPage">立即预订</up-button>
                </view>
            </view>
        </view>
        <!-- 日历组件弹窗 -->
        <up-calendar :show="showCalendar" :mode="mode" round="20" startText="住店" endText="离店"
            confirmDisabledText="请选择离店日期" :formatter="formatter" @confirm="selectDate"
            :defaultDate="defaultDateMultiple" @close="closeCalendar" :closeOnClickOverlay="true"></up-calendar>
    </view>
</template>

<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app'
import { ref, onMounted } from 'vue'
import customNavbar from '../../components/custom-navbar/index.vue'
import { orderCreateFun, roomDetailFun } from '@/api/port'

// 接口定义

// 响应式数据
const room_id = ref()
const roomInfo = ref<any>({})

const rules = ref<any>({
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    number: [
        { required: true, message: '请输入人数', trigger: 'blur' }
    ],
    datetime: [
        { required: true, message: '请选择入住和退房日期', trigger: 'blur' },
        // { type: 'array', message: '请选择入住和退房日期', trigger: 'blur' },
        // { min: 2, message: '请选择入住和退房日期', trigger: 'blur' }
    ],
    mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    // card_no: [
    //     { required: true, message: '请输入身份证号', trigger: 'blur' },
    //     { pattern: /^\d{15}$|^\d{18}$|^\d{17}(\d|X|x)$/, message: '请输入正确的身份证号', trigger: 'blur' }
    // ]
})

const formData = ref<any>({
    name: '测试',
    datetimeText: '',
    number: '1',
    mobile: '17812299070',
})

const showCalendarPopup = ref<boolean>(false)
const navHeight = ref<number>(uni.getStorageSync('navHeight') ? uni.getStorageSync('navHeight') : 88)
const datetime = ref<boolean>(false)





const onConfirmDate = (event: any): void => {
    formData.value.datetime = [formatDateFun(event.detail)]
    showCalendarPopup.value = false
}

const formatDateFun = (date: string | Date): string => {
    const dateTime = new Date(date)
    const year = dateTime.getFullYear()
    const month = dateTime.getMonth() + 1
    const day = dateTime.getDate()

    return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
}



const calculateTotalPrice = (): number => {
    const nights = calculateNights()
    const roomPrice = 299 // 每晚价格
    const serviceFee = 20 // 服务费
    const cleaningFee = 30 // 清洁费

    return roomPrice * nights + serviceFee + cleaningFee
}
const formRef = ref<UniFormRef|null>(null)
const goToPayPage = async (): void => {
    // 验证表单数据
    // if (!validateForm()) {
    //   return
    // }
    formRef.value?.validate().then(async res => {
        // toast('校验通过')
        // 构造订单数据
        const orderData: any = {
            room_id: room_id.value,
            name: formData.value.name,
            number: formData.value.number,
            phone: formData.value.mobile,
            start_date: checkInDate.value,
            end_date: checkOutDate.value,
        }
        
        // const result = await orderCreateFun(orderData)
        // if (result.code == 1) {
        //     uni.showToast({
        //         title: '下单成功',
        //         icon: 'success'
        //     })
        // }

        // 跳转到支付页面并传递订单数据
        // uni.navigateTo({
        //     url: `/subpackage/payPage/payPage?order_id=${result.data.id}`
        // })
        uni.navigateTo({
            url: `/subpackage/payPage/payPage?orderData=${encodeURIComponent(JSON.stringify(orderData))}`
        })
    }).catch(errors => {
        console.log(errors)
    })
    
}



const hideKeyboard = () => {
    uni.hideKeyboard()
}


// 日历相关数据
const showCalendar = ref<boolean>(false)
const selectedDates = ref<string[]>([])
const defaultDateMultiple = ref<string[]>([])
const closeCalendar = () => {
    showCalendar.value = false
}
const checkInDate = ref<string>('')
const checkOutDate = ref<string>('')
const checkInWeek = ref<string>('')
const checkOutWeek = ref<string>('')
const nights = ref<number>(0)
const calculateNights = () => {
    if (checkInDate.value && checkOutDate.value) {
        const checkIn = new Date(checkInDate.value)
        const checkOut = new Date(checkOutDate.value)
        const diffTime = checkOut.getTime() - checkIn.getTime()
        nights.value = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    }
}
// 选择日期
const selectDate = (dates: string[]) => {
    selectedDates.value = dates
    if (dates.length >= 2) {
        checkInDate.value = dates[0]
        checkOutDate.value = dates[dates.length - 1]
        calculateNights()
        // 计算入住周几
        const checkInDay = new Date(checkInDate.value)
        checkInWeek.value = checkInDay.toLocaleString('zh-CN', { weekday: 'long' })
        // 计算离店周几
        const checkOutDay = new Date(checkOutDate.value)
        checkOutWeek.value = checkOutDay.toLocaleString('zh-CN', { weekday: 'long' })
    }
    closeCalendar()
}
// 打开日历弹窗
const openCalendar = () => {
    showCalendar.value = true
}
// 首次进入页面获取默认日期，今天为入住日期，明天为离店日期，并为日历设置默认日期
const getDefaultDate = () => {
    console.log('22222222222')
    if (checkInDate.value && checkOutDate.value) {
        calculateNights()
    } else {
        const today = new Date()
        const tomorrow = new Date(today)
        tomorrow.setDate(tomorrow.getDate() + 1)
        checkInDate.value = today.toISOString().split('T')[0]
        checkOutDate.value = tomorrow.toISOString().split('T')[0]
        calculateNights()
    }
    // 计算入住周几
    const checkInDay = new Date(checkInDate.value)
    // 计算离店周几
    const checkOutDay = new Date(checkOutDate.value)
    checkInWeek.value = checkInDay.toLocaleString('zh-CN', { weekday: 'long' })
    // 计算离店周几
    checkOutWeek.value = checkOutDay.toLocaleString('zh-CN', { weekday: 'long' })
    // 为日历设置默认日期
    defaultDateMultiple.value = [checkInDate.value, checkOutDate.value]
    formData.value.datetimeText = `${checkInDate.value}-${checkOutDate.value} 共${nights.value}晚`
}


// 获取房间详情
const getRoomDetail = async () => {
    const res = await roomDetailFun({
        room_id: room_id.value
    })
    if (res.code === 1) {
        roomInfo.value = res.data
    }
}

const jsonToArray = (key: string, jsonData: string) => {
    if(key == 'config'){
        return JSON.parse(jsonData)
    }
}

onLoad((options)=>{
	console.log(decodeURIComponent(options.orderParmas))
	let params = JSON.parse(decodeURIComponent(options.orderParmas))
    room_id.value = params.room_id
    checkInDate.value = params.check_in
    checkOutDate.value = params.check_out
    console.log('111111111111111111',params)
    getRoomDetail()
    getDefaultDate()
})
// 生命周期钩子
onMounted(() => {
    
})
</script>
<style>
/* subpackage/book/book.wxss */
.bookPage {
    width: 100%;
    background-color: rgba(245, 245, 245, 1);
    padding: 30rpx;
    box-sizing: border-box;
}

.bookPage_info {
    width: 100%;
    padding: 25rpx 30rpx;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    background-color: #ffffff;
    border-radius: 20rpx;
}

.bookPage_info .bookPage_info_left {
    width: 194rpx;
    height: 170rpx;
}

.bookPage_info .bookPage_info_left image {
    width: 100%;
    height: 100%;
}

.bookPage_info .bookPage_info_right {
    width: calc(100% - 194rpx - 28rpx);
    height: 170rpx;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
    margin-left: 28rpx;
}

.bookPage_info .bookPage_info_right text:nth-child(1) {
    /** 文本1 */
    font-size: 28rpx;
    font-weight: bold;
    letter-spacing: 0px;
    line-height: 37.13rpx;
    color: rgba(19, 19, 19, 1);
}

.bookPage_info .bookPage_info_right text:nth-child(2) {
    /** 文本1 */
    font-size: 24rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 37.13rpx;
    color: rgba(19, 19, 19, 1);
    margin-top: 16rpx;
}

.bookPage_info .bookPage_info_right text:nth-child(3) {
    /** 文本1 */
    font-size: 24rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 37.13rpx;
    color: rgba(19, 19, 19, 1);
    margin-top: 12rpx;
}

.bookPage_form {
    width: 100%;
    margin-top: 30rpx;
    background-color: #ffffff;
    padding: 20rpx;
    box-sizing: border-box;
    border-radius: 20rpx;
}

.form-cell-group {
    margin: 0 !important;
}

.bookPage_explain {
    width: 100%;
    padding: 30rpx;
    box-sizing: border-box;
    margin-top: 30rpx;
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

.bookPage_explain text:nth-child(1) {
    /** 文本1 */
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 44rpx;
    color: rgba(0, 0, 0, 1);
}

.bookPage_explain text:nth-child(2) {
    /** 文本1 */
    font-size: 24rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 38rpx;
    color: rgba(19, 19, 19, 0.5);
}

.bookPage_footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 172rpx;
    padding: 24rpx 30rpx 0 30rpx;
    box-sizing: border-box;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
}

.bookPage_footer .bookPage_footer_left {
    display: flex;
    align-items: baseline;
    justify-content: flex-start;
}

.bookPage_footer_left_price {
    /** 文本1 */
    font-size: 40rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 57.92rpx;
    color: rgba(17, 51, 17, 1);
}

.bookPage_footer_left_particulars {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-left: 12rpx;
}

.bookPage_footer_left_particulars text {
    /** 文本1 */
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 40.54rpx;
    color: rgba(153, 153, 153, 1);
}

.bookPage_footer_left_particulars image {
    width: 14rpx;
    height: 14rpx;
}

.bookPage_footer_right {
    width: 345rpx;
    height: 80rpx;
}

.bookPage_footer_right .btn {
    width: 100%;
    height: 100%;
    margin: 0 !important;
}
</style>
